import {
    app,
    BrowserWindow
} from 'electron';
import {
    Menu,
    MenuItem,
    dialog,
    ipcMain
} from 'electron';


import { yunshanfu } from "./yunshanfu";
import { accManager } from './accountmanager';
if (require('electron-squirrel-startup')) {
    app.quit();
}

export var mainWindow;
export var safeExit = false;
function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        width: 1280,
        height: 1024,
        minWidth: 1280,
        minHeight: 1024
    });


    mainWindow.loadURL(`file://${__dirname}/index.html`);
    //mainWindow.webContents.openDevTools();
    const menu = Menu.buildFromTemplate([{
        label: '账号',
        submenu: [{
            label: '添加单个账号',
            click() {
                mainWindow.webContents.send('action', 'import');
            }
        }, {
            label: '导入账号',
            click() {
                mainWindow.webContents.send('action', 'imports');
            }
        }, {
            label: '退出全部账号',
            click() {
                accManager.ins.deleteAll();
                mainWindow.webContents.send('action', 'deleteAll');

            }
        }]
    }]);
    Menu.setApplicationMenu(menu);
    mainWindow.on('close', (e) => {

        if (!safeExit) {
            e.preventDefault();
            mainWindow.webContents.send('action', 'exiting');
        }

    });


    mainWindow.on('closed', () => {
        mainWindow = null;
    });

};

app.on('ready', createWindow);


app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (mainWindow === null) {
        createWindow();
    }
});
ipcMain.on('exit', (event, arg) => {
    safeExit = true;
    app.quit(); //退出程序
});

ipcMain.on('import', (event, user, pwd) => {
    accManager.ins.addAccount(user, pwd);
});
ipcMain.on('delete', (event, user) => {
    accManager.ins.deleteAcount(user);
});
ipcMain.on('retryCard', async (event, user) => {
    accManager.ins.retryCard(user);

});
ipcMain.on('retrySms', async (event, user) => {
    accManager.ins.retrySms(user);

});
ipcMain.on('verifySms', async (event, user, code) => {
    accManager.ins.verifySms(user, code);

});
import * as fs from "fs";
ipcMain.on('imports', (event, filename) => {
    let buf = fs.readFileSync(filename);
    let str = buf.toString();
    let arr = str.replace(/\r\n/g, "\n").split("\n");
    arr.forEach(a => {
        let as = a.split(",");
        if (as.length != 2) return;
        accManager.ins.addAccount(as[0], as[1]);
    })
    //accManager.ins.addAccount(user, pwd);
});

